package relatorios;

import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRTextExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.view.JasperViewer;
import business.dados.BancoDadosRelatorios;
import business.sistema.IObjetoSistema;

public class GeraRelatorio 
{
	/**
	 * Método responsável por gerar um relatório.
	 * 
	 * @param nomeRelatorio : String nome do arquivo, sem a extenssão, no qual o relatório foi desenhado.
	 * @param parametros
	 * @throws Exception
	 */
	public void geraRelatorio(String nomeRelatorio, String sql, Map<String,Object> parametros) throws  Exception
	{
		BancoDadosRelatorios bancoDadosRelatorio = new BancoDadosRelatorios();
		JRResultSetDataSource jrRS = new JRResultSetDataSource(bancoDadosRelatorio.getDados(sql));

		JasperFillManager.fillReportToFile("Relatorios/" + nomeRelatorio + ".jasper", parametros, jrRS);

		JasperViewer.viewReport("Relatorios/" + nomeRelatorio + ".jrprint", false, false);	
	}
	
	/**
	 * Método responsável por gerar um relatório.
	 * 
	 * @param nomeRelatorio
	 * @param parametros
	 * @throws Exception
	 */
	public static void geraRelatorio(String nomeRelatorio, Map<String,Object> parametros, List<IObjetoSistema> listaObjetos) throws Exception
	{
		JasperPrint jasperPrint = JasperFillManager.fillReport("Relatorios/" + nomeRelatorio + ".jasper", parametros, new JRBeanCollectionDataSource(listaObjetos));
		JasperViewer.viewReport(jasperPrint, false);
	}
	
	/**
	 * 
	 * 
	 * @param nomeRelatorio
	 * @param parametros
	 * @throws Exception
	 */
	public void geraRelatorioConnection(String nomeRelatorio, Map<String,Object> parametros) throws  Exception
	{
		parametros.put("SUBREPORT_DIR", "Relatorios/");
		
		Connection connection = BancoDadosRelatorios.getConnection();

		JasperPrint jasperPrint = JasperFillManager.fillReport("Relatorios/" + nomeRelatorio + ".jasper", parametros, connection);		

		JasperViewer.viewReport(jasperPrint, false);
		
		if( parametros.get("EXPORTAR_EXCEL") != null)
		{
			JRXlsExporter xls = new JRXlsExporter();
				
			xls.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			xls.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "Relatorios/" + nomeRelatorio + ".xls");
			
			xls.exportReport();
		}
		if( parametros.get("EXPORTAR_WORD") != null)
		{
			JRTextExporter doc = new JRTextExporter();
				
			doc.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			doc.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "Relatorios/" + nomeRelatorio + ".doc");
			
			doc.exportReport();
		}
	}
	
	public void imprimeRelatorio(String nomeRelatorio, String sql, Map<String,Object> parametros) throws Exception
	{
		BancoDadosRelatorios bancoDadosRelatorio = new BancoDadosRelatorios();
		JRResultSetDataSource jrRS = new JRResultSetDataSource(bancoDadosRelatorio.getDados(sql));
		
		String relatorio = "Relatorios/" + nomeRelatorio;

		JasperFillManager.fillReportToFile(relatorio + ".jasper", parametros, jrRS);
		
		
		if (JasperPrintManager.printReport(relatorio + ".jrprint", true) )
		{
			System.out.println("################" + "Relatorios/" + nomeRelatorio);
		}
	}
	
	public void geraRelatorioComSubRelatorio(String nomeRelatorio, Map<String, Object> parametros) throws  Exception
	{		
		Connection connection = BancoDadosRelatorios.getConnection();
		
		parametros.put("SUBREPORT_DIR", "Relatorios/");

		JasperFillManager.fillReportToFile("Relatorios/" + nomeRelatorio + ".jasper", parametros, connection);		

		JasperViewer.viewReport("Relatorios/" + nomeRelatorio + ".jrprint", false, false);	
	}
	
	public static void gerarRelatorioBeans(String nomeRelatorio, List<IObjetoSistema> listaObjetos, Map<String, Object> parametros) throws Exception
	{
		if(parametros == null)
		{
			parametros = new HashMap<String, Object>();
		}
		
		parametros.put("SUBREPORT_DIR", "Relatorios/");
		
		JRDataSource jrds = new JRBeanCollectionDataSource(listaObjetos);
		
		JasperPrint jrp = JasperFillManager.fillReport("Relatorios/" + nomeRelatorio + ".jasper", parametros, jrds);
		
		JasperViewer.viewReport(jrp, false);
	}

	public static void gerarRelatorioBeansWeb(String nomeRelatorio, List<Object> listaObjetos, Map<String, Object> parametros) throws JRException, IOException
	{
		if(parametros == null)
		{
			parametros = new HashMap<String, Object>();
		}
		
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
		response.setContentType("application/pdf");
		String relatorio = session.getServletContext().getRealPath("/resources/reports/" + nomeRelatorio + ".jasper"); 
		String logo = session.getServletContext().getRealPath("/resources/images/logo.png");
		
//		parametros.put("SUBREPORT_DIR", "Relatorios/");
		parametros.put("LOGO", logo);
		
		JRDataSource jrds = new JRBeanCollectionDataSource(listaObjetos);
		
		JasperPrint jrp = JasperFillManager.fillReport(relatorio, parametros, jrds);
		
		JasperExportManager.exportReportToPdfStream(jrp, response.getOutputStream());

		
		FacesContext context = FacesContext.getCurrentInstance();
		context.getApplication().getStateManager().saveView(context);
		context.responseComplete();
	}
}
